package maosui.websocket;

import maosui.model.RoomEntity;
import maosui.model.UserEntity;
import org.hibernate.Session;

public class DBManager {

    public static org.hibernate.Session session;

    static {
        session = SDB.getSession();
    }

    public static RoomEntity getRoomByCid(int cid){
        return (RoomEntity)getOne("from RoomEntity WHERE cid=" + cid);
    }

    public static RoomEntity getRoomById(int id){
        return (RoomEntity)getOne("from RoomEntity WHERE id=" + id);
    }

    public static UserEntity getUserById(int id){
        return (UserEntity)getOne("from UserEntity WHERE id = " + id);
    }

    public static Object getOne(String sql){
        if(!getSession().isConnected())return null;
        Object o = getSession().createQuery(sql).uniqueResult();
        closeSession();
        return o;
    }

    public static Session getSession() {
        if(session == null || !session.isConnected()){
            session = SDB.getSession();
        }
        return session;
    }

    public static void closeSession(){
        if(session != null && session.isConnected()){
            session.close();
            session = null;
        }
    }
}
